package com.registerandlogin;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

import javax.xml.crypto.Data;

import com.mysql.cj.exceptions.RSAException;
import com.mysql.cj.xdevapi.PreparableStatement;
import com.registerandlogin.DBUtil;
import com.sun.org.apache.regexp.internal.recompile;

import javafx.css.PseudoClass;


public class ApplicantDAO {
	public boolean isExitEmail(String email) {
			Connection conn =DBUtil.getConnection();
			PreparedStatement pstmt = null;
			ResultSet rs=null;
			String sql = "SELECT * FROM tb_applicant WHERE applicant_email = ?";
			try {
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, email);
				rs = pstmt.executeQuery();
				if (rs.next()) {
					return true;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				DBUtil.closeJDBC(rs, pstmt, conn);
			}
			return false;
	}
	
	public void save(String email,String password) {
		Connection conn = DBUtil.getConnection();
		PreparedStatement pstmt=null;
		String  sql = "INSERT INTO tb_applicant(applicant_id,applicant_email,applicant_pwd,applicant_registdate) VALUES(null,?,?,?)";
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,email);
			pstmt.setString(2, password);
			pstmt.setTimestamp(3, new Timestamp(new Date().getTime()));
			pstmt.executeLargeUpdate();
		} catch (Exception e) {
			e.printStackTrace();// TODO: handle exception
		} finally {
			DBUtil.closeJDBC(null, pstmt, conn);
		}
				
	}
	
	public int login(String email,String password) {
		int applicantID = 0;
		Connection connection=DBUtil.getConnection();
		PreparedStatement preparedStatement = null;
		ResultSet rSet = null;
		String sql = "SELECT applicant_id FROM tb_applicant WHERE applicant_email = ? and applicant_pwd = ?";
		try {
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, email);
			preparedStatement.setString(2, password);
			rSet = preparedStatement.executeQuery();
			if (rSet.next()) {
				applicantID = rSet.getInt("applicant_id");
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeJDBC(rSet,preparedStatement , connection);
		}
		
		return applicantID;
	}
	
	public int isExistResum(int applicantID){
		int resumeID = 0;
		Connection connection = DBUtil.getConnection();
		PreparedStatement pStatement = null;
		ResultSet resultSet = null;
		String sql = "SELECT basicinfo_id FROM tb_resume WHERE applicant_id = ?";
		try {
			pStatement = connection.prepareStatement(sql);
			pStatement.setInt(1, applicantID);
			resultSet=pStatement.executeQuery();
			if (resultSet.next()) {
				resumeID = resultSet.getInt(1);	
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeJDBC(resultSet, pStatement, connection);
		}
		
		return resumeID;
	
	
	}
}
